package com.xteam.xnetworkdisk.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xteam.xnetworkdisk.common.CurrentUser;
import com.xteam.xnetworkdisk.dto.UserLoginDTO;
import com.xteam.xnetworkdisk.sys.dao.FileDao;
import com.xteam.xnetworkdisk.sys.dao.UserDao;
import com.xteam.xnetworkdisk.sys.entity.LoginHistoryEntity;
import com.xteam.xnetworkdisk.sys.entity.SettingsEntity;
import com.xteam.xnetworkdisk.sys.service.LoginHistoryService;
import com.xteam.xnetworkdisk.sys.service.SettingsService;
import com.xteam.xnetworkdisk.sys.service.impl.IPService;
import com.xteam.xnetworkdisk.utils.R;
import com.xteam.xnetworkdisk.utils.ThreadPoolManager;
import com.xteam.xnetworkdisk.utilsinterface.IPUtils;
import com.xteam.xnetworkdisk.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.xteam.xnetworkdisk.sys.entity.UserEntity;
import com.xteam.xnetworkdisk.sys.service.UserService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutorService;


/**
 * 用户控制器类
 * 处理用户相关的请求
 *
 * 作者：xiaozhiyong
 * 邮箱：xiaozhiyong03@gmail.com
 * 日期：2024-08-04 15:56:30
 */
@Slf4j
@RestController
@RequestMapping("sys/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private SettingsService settingsService;

    @Autowired
    private LoginHistoryService loginHistory;

    @Autowired
    private UserDao userDao;
    @Autowired
    private FileDao fileDao;

    @Autowired
    private IPService ipService;

    /**
     * 获取用户头像
     *
     * @return 用户头像URL 'url':url
     */
    @GetMapping("/getAvatar")
    public R getAvatar(HttpSession session) {
//        Integer currentUserId = CurrentUser.getCurrentUserId();
        Integer userid = (Integer) session.getAttribute("userid");
        // 这里实现获取用户头像的逻辑
        R result = userService.getAvatar(userid);
        return result;
    }

    /**
     * 更新用户头像
     * @param avatarFile
     * @param session
     * @return
     */
    @PostMapping("/updateAvatar")
    public R updateAvatar(@RequestParam("avatar") MultipartFile avatarFile,HttpSession session) {
        Integer userid = (Integer) session.getAttribute("userid");
        // 这里实现更新用户头像的逻辑
        R result = userService.updateAvatar(userid,avatarFile);
        return result;
    }


    /**
     * 更新背景
     * @param background
     * @param session
     * @return
     */
    @PostMapping("/updateBackground")
    public R updateBackground(@RequestParam("background") MultipartFile background,HttpSession session) {
        Integer userid = (Integer) session.getAttribute("userid");
        // 这里实现更新用户头像的逻辑
        R result = userService.updateBackground(userid,background);
        return result;
    }
    /**
     * 获取用户背景
     *
     * @return 用户头像URL 'url':url
     */
    @GetMapping("/getBackground")
    public R getBackground(HttpSession session) {
//        Integer currentUserId = CurrentUser.getCurrentUserId();
        Integer userid = (Integer) session.getAttribute("userid");
        // 这里实现获取用户头像的逻辑
        R result = userService.getBackground(userid);
        return result;
    }

    /**
     * 更新用户个人信息
     * @param userModifyVO
     * @return
     */
    @PostMapping("/mod")
    public R mod(@Valid @RequestBody UserModifyVO userModifyVO){
        R result = userService.modify(userModifyVO);
        return result;
    }

    /**
     * 获取用户
     * @param
     * @return
     */
    @GetMapping("getUserInfo")
    public R getUser(){
        Integer currentUserId = CurrentUser.getCurrentUserId();
        UserEntity byId = userService.getById(currentUserId);

        if (Objects.isNull(byId)){
            return R.error("未找到相应用户");
        }

        UserLoginDTO userLoginDTO = new UserLoginDTO();
        userLoginDTO.setAge(byId.getAge());
        userLoginDTO.setUsername(byId.getUsername());
        userLoginDTO.setSex(byId.getSex());
        userLoginDTO.setName(byId.getName());
        userLoginDTO.setPhone(byId.getPhone());
        userLoginDTO.setUseSpace(byId.getUseSpace());
        userLoginDTO.setTotalSpace(byId.getTotalSpace());
        return R.ok().put("userInfo",userLoginDTO);
    }


    /**
     * 删除
     * @return
     */
    @GetMapping("/delete")
    public R delete(){
        Integer currentUserId = CurrentUser.getCurrentUserId();

        boolean remove = userService.removeById(currentUserId);
        if(!remove){
            return R.error("删除失败");
        }else{
            return R.ok("删除成功");
        }
    }

    /**
     * 分页查询
     * @param userListPageVO
     * @return
     */
    @PostMapping("/listpage")
    public R listPage(@RequestBody UserListPageVO userListPageVO){
        R result = userService.listPage(userListPageVO);
        return result;
    }


    /**
     * 验证验证码并激活账户
     * @param userRegisterVerification
     * @return
     */
    @PostMapping("verification")
    public R verify(@RequestBody UserRegisterVerificationVO userRegisterVerification,HttpServletRequest request) {

        R result = userService.verification(userRegisterVerification,request);
        return result;
    }

    /**
     * 发送验证码
     * @param userRegisterSendEmailVO
     * @return
     */
    @PostMapping("/sendEmailCaptcha")
    public R register(@Valid @RequestBody UserRegisterSendEmailVO userRegisterSendEmailVO) {
        R result = userService.register(userRegisterSendEmailVO);
        return result;
    }

    /**
     *登录
     * @param userLoginVO
     * @return
     */
    @PostMapping("login")
    public R login(@Valid @RequestBody UserLoginVO userLoginVO, HttpSession session, HttpServletRequest request) throws Exception {
        Map<String, Object> login = userService.login(userLoginVO, session);
        R result = (R) login.get("result");
        Integer userId = (Integer) login.get("userId");

        ExecutorService executorService = ThreadPoolManager.getExecutorService();

        executorService.submit(()->{
            // 新增login_history
            String[] locationByRequest = ipService.getLocationByRequest(request);
            String deviceInfo = ipService.getDeviceByRequest(request);

            String ip = locationByRequest[0];
            String location = locationByRequest[1];

            if(location == null){
                location = "未知";
            }

            Boolean i = loginHistory.loginInsert(userId,ip,location,result.getCode()==200?1:0,deviceInfo);
        });



        if (result.getCode() == 200) {
            UserLoginDTO userLoginDTO = (UserLoginDTO) result.get("userInfo");
            // 将用户ID保存到session
            session.setAttribute("userid", userId);
            session.setMaxInactiveInterval(60 * 60); // 设置Session的有效期为1小时

            // 将城市信息处理放到另一个线程中执行
            executorService.submit(() -> {
                String city = userLoginDTO.getCity();
                String[] locationByRequest = ipService.getLocationByRequest(request);
                String ip = locationByRequest[0];
                String location = locationByRequest[1];
                log.info("location:{}", location);

                // 从配置文件中读取是否进行异地登录提醒
                QueryWrapper<SettingsEntity> wrapper = new QueryWrapper<>();
                wrapper.eq("user_id", userId);
                SettingsEntity settingsEntity = settingsService.getOne(wrapper);
                Boolean abnormalEmailAlert = settingsEntity.getAbnormalEmailAlert();
                if(!abnormalEmailAlert){
                    return;
                }

                // 比对城市信息
                if (city == null || city.isEmpty()) {
                    UserEntity userEntity = userDao.selectById(userId);
                    userEntity.setCity(location); // 更新城市信息
                    userDao.updateById(userEntity);
                } else if (!city.equalsIgnoreCase(location)) {
                    // 发送提醒邮件
                    userService.loginFromANewLocationSendEmail(userLoginDTO.getUsername(), location, userLoginDTO.getName());
                }
            });

        }


        return result;
    }

    /**
     * 发送验证码到邮箱
     * @param username
     * @return
     */
    @GetMapping("/sendEmailResetP")
    public R resetpasswordsendemail(@RequestParam String username){
        R result = userService.resetPasswordSendeMail(username);
        return result;
    }

    /**
     * 输入新密码和验证码，重置密码
     * @param userResetPasswordVertifyVO
     * @return
     */

    @PostMapping("/resetPassword")
    public R verify(@Valid @RequestBody UserResetPasswordVertifyVO userResetPasswordVertifyVO){
        R result = userService.resetPasswordVerify(userResetPasswordVertifyVO);
        return result;
    }


    /**
     * 修改绑定邮箱
     * @param changeEmailVO
     * @return
     */
    @PostMapping("/changeEmail")
    public R changeEmail(@RequestBody ChangeEmailVO changeEmailVO){
        R result = userService.changeEmail(changeEmailVO);
        return result;
    }


    /**
     * 发送验证码重置邮箱
     * @param email
     * @return
     */
    @GetMapping("/sendEmailResetE")
    public R sendEmailResetE(@RequestParam("email") String email){
        R result = userService.sendEmailResetE(email);
        return result;
    }



}
